/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import <UserNotifications/UserNotifications.h>
#import "AppDelegate.h"

#import "EaseIMHelper.h"
#import "SingleCallController.h"
#import "ConferenceController.h"
#import "EMGlobalVariables.h"
#import "EMDemoOptions.h"
#import "EMNotificationHelper.h"
#import "EMHomeViewController.h"
#import "EMLoginViewController.h"
#import "UserInfoStore.h"
#import <MBProgressHUD/MBProgressHUD.h>

#define FIRSTLAUNCH @"firstLaunch"


@interface AppDelegate () //<UNUserNotificationCenterDelegate>

@end


@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    
    _connectionState = EMConnectionConnected;
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    NSString *logPath = [NSString stringWithFormat:@"%@/Library/Application Support/HyphenateSDK/easemobLog/easemob.log",NSHomeDirectory()];
    BOOL isDirectory;
    if ([NSFileManager.defaultManager fileExistsAtPath:logPath isDirectory:&isDirectory]){
        NSLog(@"文件存在,是否文件夹:%d",isDirectory);
        
        NSURL *fileURL = [NSURL fileURLWithPath:logPath];
        NSNumber *fileSize;
        NSError *error;
        if ([fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:&error]) {
            NSLog(@"文件大小为：%lld", [fileSize longLongValue]);
        } else {
            NSLog(@"获取文件大小失败：%ld", error.code);
        }
    }else{
        NSLog(@"文件不存在");
    }
    
    //注册推送
    [EMAppConfig.shared registerUserNotification];

    //初始化IM
    [self _initIM];
    [EMAppConfig.shared configBugly];
    
    [self.window makeKeyAndVisible];
    
    [EMClient.sharedClient log:[NSString stringWithFormat:@"==================:%@",launchOptions]];
    
    return YES;
}

//- (void)applicationDidEnterBackground:(UIApplication *)application{
//    [EMClient.sharedClient log:@"TEST:applicationDidEnterBackground:"];
//    [[EMClient sharedClient] applicationDidEnterBackground:application];
//}
//
//- (void)applicationWillEnterForeground:(UIApplication *)application{
//    [EMClient.sharedClient log:@"TEST:applicationWillEnterForeground:"];
//    [[EMClient sharedClient] applicationWillEnterForeground:application];
//}
- (void)applicationDidEnterBackground:(UIApplication *)application{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}

- (void)applicationWillTerminate:(UIApplication *)application{
    
}

// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    NSLog(@"====================%@", deviceToken);

    
    //objective-c 将推送令牌Data转为 string
    NSMutableString *deviceTokenString1 = [NSMutableString string];
    const char *bytes = deviceToken.bytes;
    unsigned long iCount = deviceToken.length;
    for (int i = 0; i < iCount; i++) {
        [deviceTokenString1 appendFormat:@"%02x", bytes[i]&0x000000FF];
    }
    NSLog(@"objective-c：%@", deviceTokenString1);
    
    
    /*
     swift将推送令牌Data转为 string
     let tokenComponents = deviceToken.map { data in String(format: "%02.2hhx", data) }
     let deviceTokenString = tokenComponents.joined()
     print("==========================")
     print("swift:\(deviceTokenString)")
     print("==========================")
     */
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[EMClient sharedClient] bindDeviceToken:deviceToken];
    });
}

// 注册deviceToken失败，此处失败，与环信SDK无关，一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    EMAlertView *alertView = [[EMAlertView alloc]initWithTitle:NSLocalizedString(@"registefail", nil) message:error.description];
    [alertView show];
}


//下述这两个回调方法已过时,没必要再使用
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
//{
////    if (gMainController) {
////        [gMainController jumpToChatList];
////    }
//    [[EMClient sharedClient] application:application didReceiveRemoteNotification:userInfo];
//}
//
//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
//{
////    if (gMainController) {
////        [gMainController didReceiveLocalNotification:notification];
////    }
//}



#pragma mark - IM

- (void)_initIM
{
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginStateChange:) name:ACCOUNT_LOGIN_CHANGED object:nil];

    [EMAppConfig.shared configIMClient];
    gIsInitializedSDK = YES;
    EMDemoOptions *demoOptions = [EMDemoOptions sharedOptions];
    
    NSLog(@"%@",
    EMClient.sharedClient.version
          );
          
    NSLog(@"%d",
    EMClient.sharedClient.isAutoLogin
          );
    
    if (demoOptions.isAutoLogin){
        [self loginStateDidChange_login];
    } else {
        [self loginStateDidChange_logout];
    }
    
    NSLog(@"imkit version : %@",EaseIMKitManager.shared.version);
    NSLog(@"sdk   version : %@",EMClient.sharedClient.version);
}


- (void)loginStateChange:(NSNotification *)aNotif{
    BOOL loginSuccess = [aNotif.object boolValue];
    if (loginSuccess) {//登录成功加载主窗口控制器
        [self loginStateDidChange_login];
    } else {//登录失败加载登录页面控制器
        [self loginStateDidChange_logout];
    }
}

- (void)loginStateDidChange_login{
    
    UINavigationController *navigationController = nil;
//    navigationController.navigationBar.barStyle = UIBarStyleDefault;
    navigationController = (UINavigationController *)self.window.rootViewController;
    if (!navigationController || (navigationController && ![navigationController.viewControllers[0] isKindOfClass:[EMHomeViewController class]])) {
        EMHomeViewController *homeController = [[EMHomeViewController alloc] init];
        navigationController = [[UINavigationController alloc] initWithRootViewController:homeController];
    }
    
    [[EMClient sharedClient].pushManager getPushNotificationOptionsFromServerWithCompletion:^(EMPushOptions * _Nonnull aOptions, EMError * _Nonnull aError) {
        if (!aError) {
            [[EaseIMKitManager shared] cleanMemoryUndisturbMaps];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"EMUserPushConfigsUpdateSuccess" object:nil];//更新用户重启App时，会话免打扰状态UI同步
        }
    }];
    [[EMClient sharedClient].groupManager getJoinedGroupsFromServerWithPage:0 pageSize:-1 completion:^(NSArray *aList, EMError *aError) {
        if (!aError) {
            [[NSNotificationCenter defaultCenter] postNotificationName:GROUP_LIST_FETCHFINISHED object:nil];
        }
    }];
    [EMNotificationHelper shared];
    [[UserInfoStore sharedInstance] loadInfosFromLocal];

    [EMAppConfig.shared configCallManager];
    
//        NSString* path = [[NSBundle mainBundle] pathForResource:@"huahai128" ofType:@"mp3"];
//        config.ringFileUrl = [NSURL fileURLWithPath:path];
    EMMicrosoftTranslateParams* params = [[EMMicrosoftTranslateParams alloc] init];
    params.subscriptionKey = TRANSLATE_KEY;
    params.endpoint = TRANSLATE_ENDPOINT;
    params.location = TRANSLATE_LOCATION;
    [[EMTranslationManager sharedManager] initialize];
    [[EMTranslationManager sharedManager] setTranslateParam:params];
    
    [navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar_white"] forBarMetrics:UIBarMetricsDefault];
    [navigationController.navigationBar.layer setMasksToBounds:YES];
    navigationController.view.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = navigationController;
    
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:18], NSFontAttributeName, nil]];
    [[UITableViewHeaderFooterView appearance] setTintColor:kColor_LightGray];


}
- (void)loginStateDidChange_logout{
    UINavigationController *navigationController = nil;

    EMLoginViewController *controller = [[EMLoginViewController alloc] init];
    navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    
    [navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar_white"] forBarMetrics:UIBarMetricsDefault];
    [navigationController.navigationBar.layer setMasksToBounds:YES];
    navigationController.view.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = navigationController;
    
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:18], NSFontAttributeName, nil]];
    [[UITableViewHeaderFooterView appearance] setTintColor:kColor_LightGray];

}



@end
